import 'package:get/get.dart';
import '../../../data/services/user_service.dart';
import '../../../data/services/api_service.dart';
import '../../../routes/app_pages.dart';

class MineController extends GetxController {
  // 服务实例 - GetX规范
  final UserService _userService = Get.find<UserService>();
  final ApiService _apiService = Get.find<ApiService>();

  // 响应式用户信息
  final _userName = RxnString();
  final _phoneNumber = RxnString();
  final _picUrl = RxnString();
  final _avatarUrl = RxnString();
  final _userId = RxnInt();

  // 加载状态
  final _isLoading = false.obs;

  // 系统配置相关
  final userAgreementLink = ''.obs;
  final privatePolicyLink = ''.obs;

  // Getters
  String? get userName => _userName.value;
  String? get phoneNumber => _phoneNumber.value;
  String? get picUrl => _picUrl.value;
  String? get avatarUrl => _avatarUrl.value;
  int? get userId => _userId.value;
  bool get isLoading => _isLoading.value;

  @override
  void onReady() {
    super.onReady();
    // 页面准备好后获取用户信息和系统配置
    // 每次打开页面都重新获取用户信息
    getUserInfo();
    _loadSysConfig();
  }

  @override
  void onInit() {
    super.onInit();
    print('MineController 初始化');
  }

  /// 获取系统配置（用户协议和隐私政策链接）
  Future<void> _loadSysConfig() async {
    try {
      print('🔧 个人中心 - 开始获取系统配置...');

      final response = await _apiService.getSysConfig();
      final data = response['data'] as Map<String, dynamic>?;

      if (data != null) {
        // 保存协议链接
        userAgreementLink.value = data['userAgreementLink']?.toString() ?? '';
        privatePolicyLink.value = data['privatePolicyLink']?.toString() ?? '';

        print('✅ 个人中心 - 系统配置获取成功');
        print('📄 用户协议链接: ${userAgreementLink.value}');
        print('🔒 隐私政策链接: ${privatePolicyLink.value}');
      } else {
        print('❌ 个人中心 - 系统配置数据为空');
      }
    } catch (e) {
      print('❌ 个人中心 - 获取系统配置失败: $e');
      // 设置默认值，确保不影响功能使用
      userAgreementLink.value = 'www.wasu.com';
      privatePolicyLink.value = 'www.wasu.com';
    }
  }

  /// 打开服务协议
  void openServiceAgreement() {
    if (userAgreementLink.value.isNotEmpty) {
      Get.toNamed(
        Routes.WEBVIEW,
        arguments: {'url': userAgreementLink.value, 'title': '服务协议'},
      );
    } else {
      print('服务协议链接为空');
    }
  }

  /// 打开隐私协议
  void openPrivacyAgreement() {
    if (privatePolicyLink.value.isNotEmpty) {
      Get.toNamed(
        Routes.WEBVIEW,
        arguments: {'url': privatePolicyLink.value, 'title': '隐私协议'},
      );
    } else {
      print('隐私协议链接为空');
    }
  }

  /// 获取用户信息
  Future<void> getUserInfo() async {
    try {
      _isLoading.value = true;
      print('个人中心页面开始获取用户信息...');

      final response = await _apiService.getUserInfo();
      final data = response['data'] as Map<String, dynamic>?;

      if (data != null) {
        final newUserName = data['userName'] as String?;
        final newAvatarUrl = data['picUrl'] as String?;
        final newPhoneNumber = data['phoneNumber'] as String?;
        final newUserId = data['userId'] as int?;

        _userName.value = newUserName;
        _avatarUrl.value = newAvatarUrl;
        _picUrl.value = newAvatarUrl; // 保持兼容性
        _phoneNumber.value = newPhoneNumber;
        _userId.value = newUserId;

        print('个人中心页面获取用户信息成功:');
        print('  用户名: $newUserName');
        print('  头像URL: $newAvatarUrl');

        // 强制更新界面
        update();
      }
    } catch (e) {
      print('个人中心页面获取用户信息失败: $e');
      // 不显示错误给用户，按照用户要求
    } finally {
      _isLoading.value = false;
    }
  }

  /// 退出登录
  Future<void> logout() async {
    try {
      _isLoading.value = true;

      // 调用UserService的统一登出处理方法（包含调用API）
      await _userService.handleLogout(callLogoutApi: true);

      print('用户已退出登录');
    } catch (e) {
      print('退出登录失败: $e');
      // 即使失败，也调用统一方法进行清理
      try {
        await _userService.handleLogout(callLogoutApi: false);
      } catch (cleanupError) {
        print('清理失败: $cleanupError');
      }
    } finally {
      _isLoading.value = false;
    }
  }
}
